package fons.model.query.fun;

import java.util.Collections;
import java.util.List;

import com.google.common.collect.Lists;

public class SortFun implements Function {
	private final CompareFun comp;
	private final Function list;
	
	public SortFun() {
		this(null, null);
	}
	
	public SortFun(CompareFun comp) {
		this(comp, null);
	}
	
	public SortFun(CompareFun comp, Function list) {
		this.comp = comp;
		this.list = list;
	}
	
	@Override
	public Function apply(Function other) {
		/*if (other instanceof CompareFun) {
			return new SortFun((CompareFun) other, list);
			
		/*} else if (other.apply() instanceof CompareFun) {
			return new SortFun((CompareFun) other.apply(), list);*/
		if (comp == null) {
			return new SortFun((CompareFun) other, null);
			
		} else {
			return new SortFun(comp, other);
		}
	}

	@Override
	public Function apply() {
		if (this.list == null) return this;
		
		ListFun list = (ListFun) this.list.apply();
		/*if (this.list instanceof ReferenceFun) list = (ListFun) this.list.apply();
		else if (this.list instanceof ListFun) list = (ListFun) this.list.apply(;
		else throw new IllegalStateException("Can only sort lists!");*/
		
		List<Function> functionList = Lists.newLinkedList(list.get());
		Collections.sort(functionList, new java.util.Comparator<Function>() {
			@Override
			public int compare(Function arg0, Function arg1) {
				BooleanFun b = (BooleanFun) comp.apply(arg0).apply(arg1).apply();
				if (b == BooleanFun.True) return -1;
				else return 1;
			}
		});
		return new ListFun(functionList);
	}

}
